package com.dk.goodnight.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;

/**
 * token工具类
 */
public class JWTToken {
    //过期时间
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    //私钥
    private static final String TOKEN_SECRET = "dk123456-955-666-QAZWSX-QWERTYUIOP-zxcvbnm";

    /**
     * 生成签名，15分钟过期
     *
     * @param **username**
     * @param **password**
     * @return
     */
    public static String createToken(int user_id) {
        SecretKey secretKey = Keys.hmacShaKeyFor(TOKEN_SECRET.getBytes());
        String jws = Jwts.builder()
                .signWith(secretKey)
                .claim("user_id", user_id)
                .compact();
        return jws;

    }

    /**
     * 检验token是否正确
     *
     * @param **token**
     * @return
     */
    public static String getUserName(String token) {
        SecretKey secretKey = Keys.hmacShaKeyFor(TOKEN_SECRET.getBytes());
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token);
        String userName = (String) claimsJws.getBody().get("user_name");
        return userName;
    }

    public static int  getUserId(String token) {
        SecretKey secretKey = Keys.hmacShaKeyFor(TOKEN_SECRET.getBytes());
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token);
        int  user_id = (int) claimsJws.getBody().get("user_id");
        return user_id;
    }
}
